编号以第3版为准
#15.5-4 改进最优查找树
Knuth has shown that there are always roots of optimal subtrees such that root[i, j-1] <= root[i, j] <= root[i+1, j] for all 1 <= i <= n. Use this fact to modify the OPTIMAL-BST procedure to run in Θ(n^2) time.
证明:假设已经计算出了所有大小为4的子树以及相应的root,由题中结论知 root[1,4] <= root[2,5] <= root[3,6] ...。那么大小为5的子树根将会分布在上述元素之间,即 root[1,4] <= (root[1,5]) <= root[2,5] <= (root[2,6]) <= root[3,6] ...,括号中的是待计算的root。每个待探测的root只有有限个候选,所有待探测的root加起来不超过n。
#15-1 有向无环图中的最长简单路径
给定一个有向无环图G=(V, E),边权重为实数,给定图中两个定点s和t,求s到t的最长加权简单路径。
解:假设顶点已经经过了拓扑排序,取定点集a[1 .. n],其中a[1]=s,a[n]=t,子问题为LongestPath(a[1 .. i],代码如下:
#a is topological sorted, a[0] is s, a[-1] is t
def longest(a):
#d[i] is the longest distance from a[0] to a[i]
d = [-INF]*len(a)
d[0] = 0
for i in range(1, len(a)):
for j in range(i):
wji = weight(a[j], a[i])
if wji != None and d[j] > -INF and d[j] + wji > d[i]:
d[i] = d[j] + wji
return d[-1]
#15-2 最长回文子序列
子序列不要求是连续的,比如character的最长回文子序列为carac。
解法1:O(n^3),利用最长公共子序列LCS来解,对每一个a[i],计算a[1 .. i]与a[n .. i+1]的LCS,以及a[1 .. i-1]与a[n .. i+1]的LCS+1。
解法2:O(n^2),子问题为a[i .. j]包含的最大回文,令L[i, j]为a[i .